package com.wavehi.service;

import com.wavehi.mapper.IHumanMapper;
import com.wavehi.pojo.Human;
import com.wavehi.pojo.User;
import com.wavehi.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @Author WaveHi
 * @Date 18/9/2021 上午 11:29
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
public class HumanService {
    /**
     * 添加信息
     * @param human 需要添加的实体信息
     * @return 返回false表示添加失败
     */
    public Boolean add(Human human) {
        SqlSession session = null;
        try {
            //获取数据库会话
            session = MyBatisUtils.getSession();
            //获取动态代理类
            IHumanMapper mapper = session.getMapper(IHumanMapper.class);
            //执行添加操作
            return mapper.insert(human);
        } catch (Exception e) {
            e.printStackTrace();
            if(session != null) {
                session.rollback();
                session.close();
            }
            return false;
        } finally {
            //资源的关闭
            if(session != null) {
                session.commit();
                session.close();
            }
        }
    }

    /**
     * 获取所有信息
     * @return 返回一个包含所有信息的List集合
     */
    public List<Human> list() {
        SqlSession session = null;
        try {
            //获取数据库连接
            session = MyBatisUtils.getSession();
            //获取代理对象
            IHumanMapper mapper = session.getMapper(IHumanMapper.class);
            //执行查询
            return mapper.selectAll();
        } catch (Exception e) {
            e.printStackTrace();
            if(session != null) {
                session.close();
            }
            return null;
        } finally {
            //资源的关闭
            if(session != null) {
                session.close();
            }
        }
    }
}
